package cn.yeziji.forum.utils;

import cn.yeziji.forum.common.enums.ForumCommonStatus;
import cn.yeziji.forum.common.ForumResult;
import cn.yeziji.forum.common.ResultCode;
import cn.yeziji.forum.exception.ForumException;
import cn.yeziji.forum.common.enums.status.DetailsStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.List;

/**
 * 返回工具类
 *
 * @author gzkemays
 * @since 2021/12/22 14:36
 */
public class ForumResultUtils {

  public static ForumResult error() {
    return ForumResult.builder()
        .code(ForumCommonStatus.FAIL.getCode())
        .msg(ForumCommonStatus.FAIL.getMsg())
        .build();
  }

  public static ForumResult error(Object data) {
    return ForumResult.builder()
        .code(ForumCommonStatus.FAIL.getCode())
        .msg(ForumCommonStatus.FAIL.getMsg())
        .data(data)
        .build();
  }

  public static ForumResult error(String msg) {
    return ForumResult.builder()
            .code(ForumCommonStatus.FAIL.getCode())
            .msg(msg)
            .data(null)
            .build();
  }

  public static ForumResult ok() {
    return ForumResult.builder()
        .code(ForumCommonStatus.REQUEST_SUCCESS.getCode())
        .msg(ForumCommonStatus.REQUEST_SUCCESS.getMsg())
        .build();
  }

  public static ForumResult ok(Object data) {
    return ForumResult.builder()
        .code(ForumCommonStatus.REQUEST_SUCCESS.getCode())
        .msg(ForumCommonStatus.REQUEST_SUCCESS.getMsg())
        .data(data)
        .build();
  }

  public static ForumResult ok(Object data, String msg) {
    return ForumResult.builder()
        .code(ForumCommonStatus.REQUEST_SUCCESS.getCode())
        .msg(msg)
        .data(data)
        .build();
  }

  public static ForumResult forumStatus(ForumCommonStatus status) {
    return ForumResult.builder().code(status.getCode()).msg(status.getMsg()).build();
  }

  public static ForumResult detailStatus(DetailsStatus status) {
    return ForumResult.builder().code(status.getCode()).msg(status.getMsg()).build();
  }

  public static ForumResult exception(ForumException exception) {
    return ForumResult.builder().code(exception.getCode()).msg(exception.getMsg()).build();
  }

  public static ForumResult validate(BindingResult result) {
    List<FieldError> fieldErrors = result.getFieldErrors();
    List<String> msg = new ArrayList<>();
    for (FieldError fieldError : fieldErrors) {
      msg.add(fieldError.getDefaultMessage());
    }
    return ForumResult.builder()
        .code(ResultCode.ARGS_ERROR)
        .msg(StrUtils.listToStr(msg, ","))
        .build();
  }
}
